/**
 * Created by Administrator on 2017/6/23.
 */
var http = require('http');
var cheerio = require('cheerio');
var fs = require('fs');
var request = require('request');
var url = 'http://www.zcool.com.cn/';

function getHtml (html) {
    var $C = cheerio.load(html);
    var chapters = $C('.all-work-list').find('.card-box');
    var imgSrc = [];
    chapters.each(function () {
        var img = {};
        var thisImg = $C(this).find('.card-img img');
        img.src = thisImg.attr('src');
        //img.title = thisImg.attr('title') ? thisImg.attr('title').replace(/\\|\/|\{|\}|\.|\"|\'|\-|\*|\||\ |\&/g, '') : '这个家伙很懒！居然没有写标题';
        img.title = thisImg.attr('title') ? thisImg.attr('title') : '这个家伙很懒！居然没有写标题';
        img.author = $C(this).find('.card-item a').attr('title');
        imgSrc.push(img);
    });
    return imgSrc;
}

function getImage (url, p) {
    http.get(url, function (res) {
        var html = '';
        res.on('data', function (chunk) {
            html += chunk;
        });
        res.on('end', function () {
            var imgs = getHtml (html);
            (function add (i){
                if (i < imgs.length - 1) {
                    request.head(imgs[i].src, function (err, res, body) {
                        process.on('uncaughtException',function(err){
                            i ++;
                            add(i);
                        });
                        var imageName = './downLoad/' + imgs[i].title + '.jpg';
                        request(imgs[i].src).pipe(fs.createWriteStream(imageName).on('close', function () {
                            add(++i);
                        }));
                    });
                } else {
                    url = 'http://www.zcool.com.cn/?p=' + p + '#tab_anchor';
                    getImage(url, ++p);
                }
            })(0);
        })
    }).on('err',function (e) {
        console.log('有误');
    });
}
getImage(url, 1);

